<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>验证码</title>
  <style>
    #inputCaptcha {
      height: 30px;
      vertical-align: middle;
    }
    #verificationCodeImg {
      vertical-align: middle;
      cursor: pointer;
    }
    #checkCaptcha {
      height: 40px;
      width: 100px;
    }
  </style>
</head>

<body>
<h1>输入验证码</h1>
<div id="confirm">
  <input type="text" name="inputCaptcha" id="inputCaptcha">
  <img id="verificationCodeImg" src="/captcha/get" title="看不清？换一张" />
  <input type="button" value="提交" id="checkCaptcha">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
  $("#verificationCodeImg").click(function() {
    $(this).attr('src', '/captcha/get?dt=' + new Date().getTime());
  });

  $("#checkCaptcha").click(function() {
    var inputCaptcha = $("#inputCaptcha").val();
    if (inputCaptcha.trim() === "") {
      alert("请输入验证码");
      return;
    }

    $.ajax({
      type: "POST",
      url: "/captcha/check",
      data: {
        code: $("#inputCaptcha").val()
            },
      success: function(response) {
        if (response) {
          alert("验证码正确");
          location.href = "success.html"
        } else {
          alert("验证码错误或过期");
          // 刷新验证码并清空输入框
          $("#verificationCodeImg").attr('src', '/captcha/get?dt=' + new Date().getTime());
          $("#inputCaptcha").val('');
        }
      },
      error: function() {
        alert("验证码验证失败，请重试");
        // 刷新验证码并清空输入框
        $("#verificationCodeImg").attr('src', '/captcha/get?dt=' + new Date().getTime());
        $("#inputCaptcha").val('');
      }
    });
  });
</script>
</body>

</html>
